package main

import (
	"fmt"
	"strconv"
	"sync"
	"time"
)

var (
	x int64
	wg sync.WaitGroup
	lock sync.Mutex
	rwlock sync.RWMutex
)

func write() {
	//rwlock.Lock()
	lock.Lock()
	x += 1
	time.Sleep(10 * time.Millisecond)
	//rwlock.Unlock()
	lock.Unlock()
	wg.Done()
}

func read() {
	//rwlock.RLock()
	lock.Lock()
	time.Sleep(time.Millisecond)
	//rwlock.RUnlock()
	lock.Unlock()
	wg.Done()
}
func main() {
	start := time.Now()
	for i := 0; i < 10; i++ {
		wg.Add(1)
		go write()
	}
	for i := 0; i < 10; i++ {
		wg.Add(1)
		go read()
	}
	wg.Wait()
	end := time.Now()
	fmt.Println(end.Sub(start))
	wg := sync.WaitGroup{}
	for i := 0; i < 20; i++ {
		wg.Add(1)
		go func(int2 int) {
			key := strconv.Itoa(int2)
			m.Store(key,int2)
			value, _ := m.Load(key)
			fmt.Printf("k=:%v,v:=%v\n", key, value)
			wg.Done()
		}(i)
	}
	wg.Wait()
}
//sync.map
var m = sync.Map{}


//并发单例模式
type singleton struct {}
var instance *singleton
var once sync.Once

func getInstace() *singleton {
	once.Do(func() {
		instance = &singleton{}
	})
	return instance
}